import React, { PureComponent } from 'react';
import { FormattedMessage, formatMessage } from 'umi/locale';
import {
  Spin,
  Tag,
  Menu,
  Icon,
  Dropdown,
  Avatar,
  Typography,
  Tabs,
  Badge,
  Popover,
  Divider,
  notification,
  Drawer, Tooltip, Input, Form, Button,
} from 'antd';
import Logo from '../../images/logo.png';
import qrcode from '../../images/qrcode.jpg';
import newGif from '../../images/new.gif';
import moreGif from '../../images/moreGif.jpg';
import styles from './index.less';
import find from 'lodash/find';
import { routerRedux } from 'dva/router';
import request from '@/utils/request';
import config from '@/config/config';
import { connect } from 'dva';
import BraftEditor from 'braft-editor';
import MailDetail from '../../pages/WebMail/MailDetail';
// import { SketchPicker } from 'react-color';
import { SketchPicker } from 'react-color';

const FormItem = Form.Item;
const { Paragraph } = Typography;
const { TabPane } = Tabs;

@Form.create()
class GlobalHeaderRight extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      noReadText: '',
      data: [],
      meta: {},
      editRecord: {},
      password: '',
      oldPassword: '',
      showLock: sessionStorage.getItem('showLock') ? true : false,
    };
  }

  componentDidMount() {
    const that = this;
  }

  componentWillUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
  getContrastYIQ=(hexcolor)=>{
    var r = parseInt(hexcolor.substr(1,2),16);
    var g = parseInt(hexcolor.substr(3,2),16);
    var b = parseInt(hexcolor.substr(5,2),16);
    var yiq = ((r*299)+(g*587)+(b*114))/1000;
    return (yiq >= 128) ? 'black' : 'white';
  }
  handleClick = (key) => {
    console.log('key)', key);
    const { panes, routerMapping, dispatch } = this.props;
    const activeKey = key;
    if (find(panes, o => o.key == activeKey)) {
      console.log('已经存在');
    } else {
      panes.push({
        title: find(routerMapping, o => o.path == activeKey).name,
        content: 'New Tab Pane',
        key: activeKey,
      });
    }
    dispatch(routerRedux.push(activeKey));
    dispatch({
      type: 'global/changePanesAndActive',
      payload: { panes, activeKey },
    });
  };
  keyPress = (e) => {
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      console.log(this.state.oldPassword);
      this.login();
    }

  };
  getColor=()=>{
    return <div >
      <SketchPicker
        color={ this.props.background }
        onChangeComplete={ this.props.changeColor }
      />
      <Button type={'primary'} block onClick={this.props.resetBackground}>恢复默认顶部背景</Button>
    </div>;
  }
  login = () => {
    const that = this;
    request('/login', {
      method: 'POST',
      data: {
        username: this.props.currentUser.username,
        password: this.state.oldPassword,
      },
    }).then((response) => {
      if (response.status === 200) {
        this.setState({
          showLock: false,
          password: '',
          oldPassword: '',
        }, function() {
          sessionStorage.setItem('showLock', '');
        });
      }
    });
  };

  render() {
    const {
      currentUser,
      fetchingNotices,
      onNoticeVisibleChange,
      onMenuClick,
      onNoticeClear,
      theme,
    } = this.props;
    // const textColor=this.getContrastYIQ(this.props.background);
    const textColor='#fff';
    const {
      form: { getFieldDecorator },
    } = this.props;
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
        <Menu.Item key="changePassword">
          <Icon type="solution"/>修改密码
        </Menu.Item>
        <Menu.Item key="logout">
          <Icon type="logout"/>
          <FormattedMessage id="menu.account.logout" defaultMessage="logout"/>
        </Menu.Item>
      </Menu>
    );
    let className = styles.right;
    if (theme === 'dark') {
      className = `${styles.right}  ${styles.dark}`;
    }
    const username = sessionStorage.getItem('username');
    return (
      <div className={className}>

        <span className={styles.noticeButton} onClick={() => {
          this.setState({
            showLock: true,
          }, function() {
            sessionStorage.setItem('showLock', '1');
            document.querySelector('#password_input').focus();
          });
        }}>
              <Tooltip placement="left" title={'锁屏'}>
             <Avatar style={{ backgroundColor: '#2f54eb ' }} size={'small'}
                     icon={<Icon type="lock" style={{ color: '#fff' }}/>} className={styles.icon}/>
            </Tooltip>
         </span>
        <Popover
          placement="bottomRight"
          content={this.getColor()}
          popupClassName={styles.pickColor}
          trigger="click"
          arrowPointAtCenter
        >
          <span className={styles.noticeButton}>
                                 <Avatar style={{ backgroundColor: '#2f54eb ' }} size={'small'}
                                         icon={<Icon type="bg-colors" style={{ color: '#fff' }} className={styles.icon}/>}/>

         </span>
        </Popover>
     {/*   <Popover
          placement="bottomRight"
          content={this.getColor()}
          popupClassName={styles.pickColor}
          trigger="click"
          arrowPointAtCenter
        >
          <span className={styles.noticeButton}>
                                 <Avatar style={{ backgroundColor: '#273f9b ' }} size={'small'}
                                         icon={<Icon type="bg-colors" style={{ color: '#fff' }} className={styles.icon}/>}/>

         </span>
        </Popover>*/}
        {currentUser.username ? (
          <Dropdown overlay={menu}>
            <span className={`${styles.action} ${styles.account}`}>
                <Avatar src={Logo} className={styles.avatar}/>
              <span style={{ color: textColor, fontWeight: 'bold' }} className={styles.name}>{currentUser.username}</span>
            </span>
          </Dropdown>
        ) : (
          <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }}/>
        )}
        {/*  <SelectLang className={styles.action} />*/}
        <Drawer
          title={this.state.editRecord.title}
          placement="right"
          onClose={() => {
            this.setState({
              editModal: false,
              editRecord: {},
            });
          }}
          width={800}
          destroyOnClose
          visible={this.state.editModal}
        >
          <MailDetail

            editRecord={this.state.editRecord}
            wrappedComponentRef={(inst) => this.AddForm = inst}
          />
        </Drawer>
        <div className={styles.lock_container} style={{ display: this.state.showLock ? 'block' : 'none' }}>
          <div className={styles.lock_mask}></div>
          <div className={styles.lock_content}>
            <div className={styles.lock_icon}>
              <Avatar size={'large'} style={{ backgroundColor: '#009688', fontSize: '20px' }} icon="user"/>
            </div>
            <p style={{ color: '#009688', fontSize: '16px', lineHeight: '1', marginBottom: '16px' }}>
              {currentUser.username}
            </p>
            <div>
              <Form layout="inline">
                <FormItem label="">

                  <Input onFocus={(e) => {
                  }} onChange={(e) => {
                    const _this = e.target;
                    var newPassword = _this.value;
                    var oldPassword = this.state.oldPassword;
                    var truePassword = '';
                    var p = _this.selectionEnd;//光标结束时的位置

                    for (var i = 0; i < newPassword.length; i++) {
                      var c = newPassword.charAt(i);
                      if (i < p && c != '●') {
                        truePassword += c;
                      } else if (i < p && c == '●') {
                        truePassword += oldPassword.charAt(i);
                      } else {
                        truePassword += oldPassword.substr(oldPassword.length - newPassword.length + p, newPassword.length - p);
                        break;
                      }

                    }
                    newPassword = truePassword.replace(/./g, '●');
                    this.setState({
                      oldPassword: truePassword,
                    });
                    // document.querySelector('#hidden').value=truePassword;
                    this.setState({
                      password: newPassword,
                    });
                    console.log('_this.value = newPassword');
                    // _this.value = newPassword;

                    // 解决在win8中光标总是到input框的最后
                    _this.selectionEnd = p;
                    _this.selectionStart = p;

                  }} value={this.state.password} id={'password_input'} autoComplete="off" type={'text'}
                         style={{ width: '180px' }} className={styles.lock_input} placeholder="请输入密码解锁..."
                         onKeyPress={this.keyPress}/>
                  <Input id={'hidden'} value={this.state.oldPassword} type={'hidden'}/>
                </FormItem>
                <FormItem label="" style={{ marginRight: '0' }}>
                  <Button type={'primary'} icon={'unlock'} className={styles.lock_input}
                          onClick={this.login}>解锁</Button>
                </FormItem>
              </Form>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default connect(({ global, devices, setting }) => ({
  activeKey: global.activeKey,
  routerMapping: global.routerMapping,
  panes: global.panes,
  ...setting,
}))(GlobalHeaderRight);
